<?php


namespace app\admin\controller;


use app\BaseController;
use think\exception\ValidateException;
use think\facade\Filesystem;
use think\Image;
use think\response\Json;

class Upload extends BaseController
{
    /**
     * 上传图片
     *
     * @return Json
     */
    public function image (): Json
    {
        $width = intval($this->request->get('w'));
        $height = intval($this->request->get('h'));
        // 获取表单上传文件
        $file = request()->file('uploadImage');
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:10240|fileExt:jpg|image:200,200,jpg'])
                ->check(array($file));
            $filename = Filesystem::disk('public')->putFile( 'article/image', $file);
            $filename = '/upload/'.str_replace("\\","/",$filename);
            if ($width > 0 && $height > 0) {
                $image = Image::open('./'.$filename);
                $image->thumb($width, $height)->save('./'.$filename);
            }
            $data['url'] = $filename;
            return success($data);
        } catch (ValidateException $e) {
            return error(500, $e->getMessage());
        }
    }

    /**
     * 上传图片
     *
     * @return Json
     */
    public function video (): Json
    {
        // 获取表单上传文件
        $file = request()->file('uploadVideo');
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:102400|fileExt:mp4'])
                ->check(array($file));
            $filename = Filesystem::disk('public')->putFile( 'article/video', $file);
            $data['url'] = '/upload/'.str_replace("\\","/",$filename);
            return success($data);
        } catch (ValidateException $e) {
            return error(500, $e->getMessage());
        }
    }
}